<template>
  <div class="order-detail" v-loading="loading">
    <div class="page-header">
      <h2>订单详情</h2>
      <el-button @click="$router.push('/orders')">返回订单列表</el-button>
    </div>
    
    <el-card v-if="order" class="box-card">
      <div slot="header" class="clearfix">
        <span>基本信息</span>
        <el-select v-model="order.status" style="float: right; width: 120px" size="mini" @change="updateOrderStatus">
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div class="order-info">
        <div class="info-item">
          <span class="label">订单编号:</span>
          <span class="value">{{ order.orderId }}</span>
        </div>
        <div class="info-item">
          <span class="label">下单时间:</span>
          <span class="value">{{ formatDate(order.orderDate) }}</span>
        </div>
        <div class="info-item">
          <span class="label">订单金额:</span>
          <span class="value">{{ order.totalAmount }} 元</span>
        </div>
        <div class="info-item">
          <span class="label">订单状态:</span>
          <span class="value">
            <el-tag :type="getStatusType(order.status)">{{ getStatusText(order.status) }}</el-tag>
          </span>
        </div>
      </div>
    </el-card>
    
    <el-card v-if="order && order.customer" class="box-card" style="margin-top: 20px">
      <div slot="header" class="clearfix">
        <span>客户信息</span>
      </div>
      <div class="customer-info">
        <div class="info-item">
          <span class="label">客户编号:</span>
          <span class="value">{{ order.customer.customerId }}</span>
        </div>
        <div class="info-item">
          <span class="label">客户名称:</span>
          <span class="value">{{ order.customer.name }}</span>
        </div>
        <div class="info-item">
          <span class="label">联系电话:</span>
          <span class="value">{{ order.customer.phone || '无' }}</span>
        </div>
        <div class="info-item">
          <span class="label">电子邮箱:</span>
          <span class="value">{{ order.customer.email }}</span>
        </div>
        <div class="info-item">
          <span class="label">联系地址:</span>
          <span class="value">{{ order.customer.address || '无' }}</span>
        </div>
      </div>
    </el-card>
    
    <el-card class="box-card" style="margin-top: 20px">
      <div slot="header" class="clearfix">
        <span>订单商品</span>
      </div>
      <el-table
        :data="order && order.orderItems ? order.orderItems : []"
        border
        style="width: 100%">
        <el-table-column
          prop="itemId"
          label="项目ID"
          width="80">
        </el-table-column>
        <el-table-column
          label="商品名称"
          min-width="180">
          <template slot-scope="scope">
            {{ scope.row.product ? scope.row.product.name : '未知商品' }}
          </template>
        </el-table-column>
        <el-table-column
          label="单价"
          width="100">
          <template slot-scope="scope">
            {{ scope.row.unitPrice }} 元
          </template>
        </el-table-column>
        <el-table-column
          prop="quantity"
          label="数量"
          width="100">
        </el-table-column>
        <el-table-column
          label="小计"
          width="100">
          <template slot-scope="scope">
            {{ (scope.row.unitPrice * scope.row.quantity).toFixed(2) }} 元
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <el-card class="box-card" style="margin-top: 20px" v-if="delivery">
      <div slot="header" class="clearfix">
        <span>配送信息</span>
        <el-select v-model="delivery.status" style="float: right; width: 120px" size="mini" @change="updateDeliveryStatus">
          <el-option
            v-for="item in deliveryStatusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div class="delivery-info">
        <div class="info-item">
          <span class="label">配送编号:</span>
          <span class="value">{{ delivery.deliveryId }}</span>
        </div>
        <div class="info-item">
          <span class="label">配送地址:</span>
          <span class="value">{{ delivery.shippingAddress }}</span>
        </div>
        <div class="info-item">
          <span class="label">配送公司:</span>
          <span class="value">{{ delivery.carrier }}</span>
        </div>
        <div class="info-item">
          <span class="label">运单编号:</span>
          <span class="value">{{ delivery.trackingNumber || '无' }}</span>
        </div>
        <div class="info-item">
          <span class="label">配送状态:</span>
          <span class="value">
            <el-tag :type="getDeliveryStatusType(delivery.status)">{{ getDeliveryStatusText(delivery.status) }}</el-tag>
          </span>
        </div>
        <div class="info-item">
          <span class="label">预计送达:</span>
          <span class="value">{{ delivery.estimatedDelivery ? formatDate(delivery.estimatedDelivery, 'YYYY-MM-DD') : '无' }}</span>
        </div>
        <div class="info-item">
          <span class="label">实际送达:</span>
          <span class="value">{{ delivery.actualDelivery ? formatDate(delivery.actualDelivery, 'YYYY-MM-DD') : '无' }}</span>
        </div>
      </div>
    </el-card>
    
    <el-card class="box-card" style="margin-top: 20px" v-if="!delivery && order && (order.status === 'paid' || order.status === 'pending')">
      <div slot="header" class="clearfix">
        <span>创建配送信息</span>
      </div>
      <el-form :model="deliveryForm" :rules="deliveryRules" ref="deliveryForm" label-width="100px">
        <el-form-item label="收货地址" prop="shippingAddress">
          <el-input type="textarea" v-model="deliveryForm.shippingAddress" rows="3"></el-input>
        </el-form-item>
        <el-form-item label="配送公司" prop="carrier">
          <el-input v-model="deliveryForm.carrier"></el-input>
        </el-form-item>
        <el-form-item label="预计送达" prop="estimatedDelivery">
          <el-date-picker
            v-model="deliveryForm.estimatedDelivery"
            type="date"
            placeholder="选择预计送达日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="createDelivery">创建配送</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import orderApi from '@/api/order'
import deliveryApi from '@/api/delivery'
import moment from 'moment'

export default {
  name: 'OrderDetail',
  
  data() {
    return {
      loading: true,
      order: null,
      delivery: null,
      statusOptions: [
        { value: 'pending', label: '待处理' },
        { value: 'paid', label: '已支付' },
        { value: 'shipped', label: '已发货' },
        { value: 'delivered', label: '已送达' },
        { value: 'cancelled', label: '已取消' }
      ],
      deliveryStatusOptions: [
        { value: 'processing', label: '处理中' },
        { value: 'shipped', label: '已发货' },
        { value: 'in_transit', label: '运输中' },
        { value: 'delivered', label: '已送达' }
      ],
      deliveryForm: {
        orderId: null,
        shippingAddress: '',
        carrier: '',
        estimatedDelivery: null
      },
      deliveryRules: {
        shippingAddress: [
          { required: true, message: '请输入收货地址', trigger: 'blur' }
        ],
        carrier: [
          { required: true, message: '请输入配送公司', trigger: 'blur' }
        ]
      }
    }
  },
  
  created() {
    const orderId = this.$route.params.id
    if (orderId) {
      this.fetchOrderDetail(orderId)
      this.fetchDelivery(orderId)
      this.deliveryForm.orderId = parseInt(orderId)
    }
  },
  
  methods: {
    // 获取订单详情
    async fetchOrderDetail(orderId) {
      this.loading = true
      try {
        const response = await orderApi.getOrder(orderId)
        this.order = response.data
        this.loading = false
      } catch (error) {
        this.$message.error('获取订单详情失败')
        this.loading = false
      }
    },
    
    // 获取配送信息
    async fetchDelivery(orderId) {
      try {
        const response = await deliveryApi.getDeliveryByOrderId(orderId)
        if (response.data && !response.data.error) {
          this.delivery = response.data
        }
      } catch (error) {
        // 配送信息可能不存在，忽略错误
      }
    },
    
    // 创建配送
    async createDelivery() {
      this.$refs.deliveryForm.validate(async (valid) => {
        if (valid) {
          try {
            const delivery = {
              ...this.deliveryForm,
              status: 'processing'
            }
            
            const response = await deliveryApi.addDelivery(delivery)
            if (response.data.success) {
              this.$message.success(response.data.message)
              this.fetchDelivery(this.order.orderId)
              this.fetchOrderDetail(this.order.orderId)
            } else {
              this.$message.error(response.data.message)
            }
          } catch (error) {
            this.$message.error('创建配送信息失败')
          }
        } else {
          return false
        }
      })
    },
    
    // 更新订单状态
    async updateOrderStatus(status) {
      try {
        const response = await orderApi.updateOrderStatus(this.order.orderId, status)
        if (response.data.success) {
          this.$message.success(response.data.message)
          this.fetchOrderDetail(this.order.orderId)
        } else {
          this.$message.error(response.data.message)
        }
      } catch (error) {
        this.$message.error('更新订单状态失败')
      }
    },
    
    // 更新配送状态
    async updateDeliveryStatus(status) {
      try {
        const response = await deliveryApi.updateDeliveryStatus(this.delivery.deliveryId, status)
        if (response.data.success) {
          this.$message.success(response.data.message)
          this.fetchDelivery(this.order.orderId)
          this.fetchOrderDetail(this.order.orderId)
        } else {
          this.$message.error(response.data.message)
        }
      } catch (error) {
        this.$message.error('更新配送状态失败')
      }
    },
    
    // 格式化日期
    formatDate(date, format = 'YYYY-MM-DD HH:mm:ss') {
      return moment(date).format(format)
    },
    
    // 获取状态类型
    getStatusType(status) {
      const map = {
        'pending': 'info',
        'paid': 'success',
        'shipped': 'primary',
        'delivered': 'success',
        'cancelled': 'danger'
      }
      return map[status] || 'info'
    },
    
    // 获取状态文本
    getStatusText(status) {
      const map = {
        'pending': '待处理',
        'paid': '已支付',
        'shipped': '已发货',
        'delivered': '已送达',
        'cancelled': '已取消'
      }
      return map[status] || status
    },
    
    // 获取配送状态类型
    getDeliveryStatusType(status) {
      const map = {
        'processing': 'info',
        'shipped': 'primary',
        'in_transit': 'warning',
        'delivered': 'success'
      }
      return map[status] || 'info'
    },
    
    // 获取配送状态文本
    getDeliveryStatusText(status) {
      const map = {
        'processing': '处理中',
        'shipped': '已发货',
        'in_transit': '运输中',
        'delivered': '已送达'
      }
      return map[status] || status
    }
  }
}
</script>

<style scoped>
.order-detail {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.info-item {
  margin-bottom: 10px;
  display: flex;
}

.label {
  width: 100px;
  color: #606266;
}

.value {
  color: #303133;
  font-weight: bold;
}

.el-form {
  max-width: 500px;
}
</style> 